#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2018/8/15 17:21
# @Author  : youfeng
import random
import time

import requests

from enum.proxy_key import ProxyKey
from ext.proxy_base import ProxyBase

# 标注类名
__CLASS__ = "ProxyYun"
# 标注是否使用当前代理
__USED__ = True


class ProxyYun(ProxyBase):
    # 代理唯一标识
    __TAG__ = "yun"

    __YUNPROXY_API = 'http://dly.134t.com/query.txt?key=NP5C776178&word=&count=1000&detail=true'
    __YUNPROXY_AUTH = {"username": "datamonitor", "password": "555556"}

    def __init__(self, log):
        super(ProxyYun, self).__int__(log=log)

    def get_proxy_tag(self):
        return self.__TAG__

    def __parse_yun_proxy(self, line_info):
        try:
            current_time = int(time.time())
            proxy = line_info.split(",")[0]
            live_time = int(line_info.split(",")[4])

            # 限制存活时间
            if live_time - current_time > self._PROXY_MAX_TTL:
                live_time = current_time + self._PROXY_MAX_TTL

            return proxy, live_time
        except Exception as e:
            self.log.error("解析云代理异常:")
            self.log.exception(e)

        return None, None

    # 返回代理
    def get_proxy_list(self):

        username = self.__YUNPROXY_AUTH["username"]
        password = self.__YUNPROXY_AUTH["password"]

        for _ in xrange(3):
            proxy_list = []
            proxy_set = set()
            try:
                r = requests.get(self.__YUNPROXY_API, timeout=10)
                if r is None or r.status_code != 200:
                    self.log.error("更新云代理网络异常...")
                    time.sleep(random.randint(1, 2))
                    continue

                line_list = r.text.strip().split('\n')
                for line in line_list:
                    line = line.strip().strip("\r").strip("\n")
                    if len(line) <= 0:
                        continue

                    ip, expire_time = self.__parse_yun_proxy(line)
                    if ip is None:
                        continue

                    if ip in proxy_set:
                        continue

                    proxy_set.add(ip)

                    proxy = 'http://{}:{}@{}'.format(username, password, ip)
                    proxy_list.append({
                        ProxyKey.EXPIRE_TIME_KEY: expire_time,
                        ProxyKey.PROXY_KEY: proxy
                    })

                self.log.info('从云代理官网更新代理成功: length = {}'.format(len(proxy_list)))
                return proxy_list
            except Exception as e:
                self.log.error('访问云代理链接异常: ')
                self.log.exception(e)
                time.sleep(random.randint(1, 2))
        return []
